package com.lb.shopguide.ui.fragment.guide;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterGuideActivity;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.GuideActivityBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by kang on 2017/8/3.
 */
public class FragmentActivityList extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    private List<GuideActivityBean> mActivityList;

    private AdapterGuideActivity mAdapterGuideActivity;


    public static FragmentActivityList newInstance() {
        return new FragmentActivityList();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_activity_center;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        mActivityList = new ArrayList<>();
        sendRequestGetActivity();
    }

    @Override
    public void initView() {
        ntb.setTitleText("活动中心");
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));

        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂时没有活动");

        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterGuideActivity = new AdapterGuideActivity(R.layout.item_activity_item, mActivityList);
        mRecyclerView.setAdapter(mAdapterGuideActivity);
        mAdapterGuideActivity.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mActivityList.size() > position) {
                    GuideActivityBean bean = mActivityList.get(position);
                    Intent intent = new Intent(mContext, ActivityActivityDetail.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(AppConstant.WEB_URL, bean.getActLinkPath() + "?token=" + mUserConfigManager.getUserToken() + "&type=android");
//                bundle.putString(AppConstant.WEB_URL, "http://192.168.1.49:8088/activity/middleAutumn" + "?token=" + mUserConfigManager.getUserToken() + "&type=android");
//                    bundle.putString(AppConstant.WEB_TITLE, bean.getActivityName());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void finishRefresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentActivityList.class.getName();
    }


    private void bindEmpty() {
        mActivityList.clear();
        mAdapterGuideActivity.setNewData(mActivityList);

        mNoData = true;
        onRefresh();
    }


    @Override
    public void onRefresh() {
        mAdapterGuideActivity.setEnableLoadMore(false);
        if (mError) {
            mAdapterGuideActivity.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterGuideActivity.setEmptyView(noDataView);
                mNoData = false;
            } else {
                sendRequestGetActivity();
            }
        }
    }

    private void sendRequestGetActivity() {
        mActivityList = new ArrayList<>();
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonActivitys = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonActivitys.size() != 0) {
                        for (JsonElement obj : jsonActivitys) {
                            GuideActivityBean bean = JsonUtil.getGson().fromJson(obj, GuideActivityBean.class);
                            mActivityList.add(bean);
                        }
                        mAdapterGuideActivity.setNewData(mActivityList);
                    } else {
                        bindEmpty();
                    }
                    finishRefresh();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        ApiMethodGuide.getActivity(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

}
